package com.xishu.controller;

import com.xishu.aop.Validator;
import com.xishu.config.Constant;
import com.xishu.entity.foodpanda.Product;
import com.xishu.entity.shop.CompanyMainItem;
import com.xishu.entity.shop.Item;
import com.xishu.response.ResponseData;
import com.xishu.response.VerifyUtil;
import com.xishu.service.CommonService;
import com.xishu.service.CustomerService;
import com.xishu.service.ItemService;
import com.xishu.service.ZhEnService;
import com.xishu.util.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

import static com.xishu.response.ResponseStatus.NAME_EXISTS;
import static com.xishu.response.ResponseStatus.PRIVILEGE;

@Api(description = "主菜")
@RestController
public class CompanyMainItemController implements Tools {
    private static Logger logger = LoggerFactory.getLogger(CompanyMainItem.class);
    private CommonService commonService = CommonService.getInstance();
    private CustomerService customerService = CustomerService.getInstance();
    private ItemService itemService = ItemService.getInstance();

    @ApiOperation(value = "创建一个主菜")
    @PostMapping(value = ("/company/main/item"), produces = ("application/json;charset=UTF-8"))
    public ResponseData create(@RequestBody CompanyMainItem companyMainItem) throws Exception {
        String name = companyMainItem.getName();
        Long companyId = companyMainItem.getCompanyId();
        VerifyUtil.isEmpty(name, companyId);

        VerifyUtil.verify(() -> new Validator().companyRelated(companyId), PRIVILEGE);

        //处理国际化
        ZhEnService zhEnService = ZhEnService.getInstance();
        zhEnService.dealZhEn(companyMainItem);

        //同一个餐厅的菜不能重名
        Optional<CompanyMainItem> companyMainItemOptional = customerService.isCompanyMainItemExist(companyId, name, companyMainItem.getItemType());
        VerifyUtil.verify(() -> !companyMainItemOptional.isPresent(), NAME_EXISTS);

        return commonService.createObject(companyMainItem);
    }

    @ApiOperation(value = "修改一个主菜")
    @PutMapping(value = ("/company/main/item/modify"), produces = ("application/json;charset=UTF-8"))
    public ResponseData modify(@RequestBody CompanyMainItem companyMainItem) throws Exception {
        Long companyMainItemId = companyMainItem.getId();
        CompanyMainItem companyMainItemInDb = commonService.findEntity(companyMainItemId, CompanyMainItem.class);
        Long companyId = companyMainItemInDb.getCompanyId();

        VerifyUtil.verify(() -> new Validator().companyRelated(companyId), PRIVILEGE);

        if (isNotEmpty(companyMainItem.getName_zh())) {
            Optional<CompanyMainItem> companyMainItemOptional = customerService.isCompanyMainItemExist(companyId, companyMainItem.getName_zh(), companyMainItemInDb.getItemType());

            //找到名称相同，但是不同ID的
            if (companyMainItemOptional.isPresent() && !equals(companyMainItemOptional.get().getId(), companyMainItemId)) {
                VerifyUtil.verify(() -> !companyMainItemOptional.isPresent(), NAME_EXISTS);
            }
        }

        if (isNotEmpty(companyMainItem.getName_en())) {
            Optional<CompanyMainItem> companyMainItemOptional = customerService.isCompanyMainItemExist(companyId, companyMainItem.getName_en(), companyMainItemInDb.getItemType());

            //找到名称相同，但是不同ID的
            if (companyMainItemOptional.isPresent() && !equals(companyMainItemOptional.get().getId(), companyMainItemId)) {
                VerifyUtil.verify(() -> !companyMainItemOptional.isPresent(), NAME_EXISTS);
            }
        }

        return commonService.updateObject(companyMainItem, (c) -> {
            try {
                //同步修改
                List<Item> itemList = itemService.findAllItemByCompanyMainItemId(companyId, companyMainItemId);
                for (Item item : itemList) {
                    if (isNotEmpty(companyMainItem.getName_zh())) {
                        item.setName_zh(companyMainItem.getName_zh());
                    }

                    if (isNotEmpty(companyMainItem.getName_en())) {
                        item.setName_en(companyMainItem.getName_en());
                    }

                    commonService.save(item);

                    //同步修改foodpanda的菜
                    itemService.sycAllFoodPandaProduct(item.id, companyId, companyMainItem);

                    //同步修改每一个菜
                    //如果要修改的规格，跟普通的套餐规格一样的
                    itemService.itemNameSyncToOther(item.id);
                    itemService.syncItemNameInSetMenu(itemService.findItem(item.id));
                }
            } catch (Exception e) {
                logger.error("e", e);
            }
        });
    }

    @ApiOperation(value = "查询一个主菜")
    @PutMapping(value = ("/company/main/item"), produces = ("application/json;charset=UTF-8"))
    public ResponseData find(@RequestBody CompanyMainItem companyMainItem) throws Exception {
        //如果前端没有传分页的数量，服务器这里默认是999条
        if (companyMainItem.pageSize == null) {
            companyMainItem.pageSize = Constant.SEARCH_ALL_PAGE_SIZE;
        }

        companyMainItem.setSortField(new String[]{"createTime"});
        companyMainItem.setSortType("DESC");
        return commonService.searchResponse(companyMainItem);
    }

    @ApiOperation(value = "删除一个主菜")
    @DeleteMapping(value = ("/company/main/item"), produces = ("application/json;charset=UTF-8"))
    public ResponseData delete(@RequestBody CompanyMainItem companyMainItem) throws Exception {
        Long companyMainItemId = companyMainItem.getId();
        CompanyMainItem companyMainItemInDb = commonService.findEntity(companyMainItemId, CompanyMainItem.class);
        Long companyId = companyMainItemInDb.getCompanyId();

        VerifyUtil.verify(() -> new Validator().companyRelated(companyId), PRIVILEGE);

        return commonService.delete(companyMainItem, true, (c) -> {
            try {

                List<Item> itemList = itemService.findAllItemByCompanyMainItemId(companyId, companyMainItemId);
                for (Item item : itemList) {
                    commonService.delete(item);
                }
            } catch (Exception e) {
                logger.error("e", e);
            }
        });
    }
}
